<?php
// 注册标签云小工具
class Custom_Tags_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'custom_tags_widget',
            __('标签云', 'my-simple-theme'),
            array('description' => __('显示美观的标签云', 'my-simple-theme'))
        );
    }

    public function widget($args, $instance) {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }
        
        $tags = get_tags(array(
            'orderby' => 'count',
            'order' => 'DESC',
            'number' => isset($instance['number']) ? $instance['number'] : 20
        ));
        
        if ($tags) {
            echo '<div class="tag-cloud">';
            foreach ($tags as $tag) {
                $tag_link = get_tag_link($tag->term_id);
                $tag_size = 12 + ($tag->count * 0.5); // 根据标签使用次数调整大小
                echo '<a href="' . esc_url($tag_link) . '" class="tag-item" style="font-size: ' . $tag_size . 'px;">' . $tag->name . '</a>';
            }
            echo '</div>';
        } else {
            echo '<p>' . __('暂无标签', 'my-simple-theme') . '</p>';
        }
        
        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('热门标签', 'my-simple-theme');
        $number = !empty($instance['number']) ? $instance['number'] : 20;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('标题:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('显示数量:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="number" min="1" value="<?php echo esc_attr($number); ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['number'] = (!empty($new_instance['number'])) ? absint($new_instance['number']) : 20;
        return $instance;
    }
}

// 注册小工具
function register_custom_widgets() {
    register_widget('Custom_Tags_Widget');
}
add_action('widgets_init', 'register_custom_widgets');
